/*
 *    Copyright (c) 2018-2025, cloud All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: cloud
 */

package com.fuyao.cloud.asset.budget.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fuyao.cloud.asset.vo.BudgetExcelImportVO;
import com.fuyao.cloud.asset.vo.BudgetExcelVO;
import com.fuyao.cloud.common.core.util.R;
import com.fuyao.cloud.common.excel.annotation.RequestExcel;
import com.fuyao.cloud.common.log.annotation.SysLog;
import com.fuyao.cloud.asset.entity.AssetBudget;
import com.fuyao.cloud.asset.budget.service.AssetBudgetService;
import com.fuyao.cloud.common.security.service.CloudUser;
import com.fuyao.cloud.common.security.util.SecurityUtils;
import lombok.SneakyThrows;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.access.prepost.PreAuthorize;
import com.fuyao.cloud.common.excel.annotation.ResponseExcel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.UUID;

/**
 * 预算管理
 *
 * @author 时间的朋友
 * @date 2021-11-12 18:53:46
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/fyassetbudget" )
@Api(value = "fyassetbudget", tags = "预算管理管理")
public class AssetBudgetController {

    private final AssetBudgetService fyAssetBudgetService;

    /**
     * 分页查询
     * @param page 分页对象
     * @param fyAssetBudget 预算管理
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/page" )
    @PreAuthorize("@pms.hasPermission('budget_fyassetbudget_view')" )
    public R getFyAssetBudgetPage(Page page, AssetBudget fyAssetBudget) {
        return R.ok(fyAssetBudgetService.page(page, Wrappers.query(fyAssetBudget)));
    }


    /**
     * 通过id查询预算管理
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping("/{id}" )
    @PreAuthorize("@pms.hasPermission('budget_fyassetbudget_view')" )
    public R getById(@PathVariable("id" ) Long id) {
        return R.ok(fyAssetBudgetService.getById(id));
    }

    /**
     * 新增预算管理
     * @param fyAssetBudget 预算管理
     * @return R
     */
    @ApiOperation(value = "新增预算管理", notes = "新增预算管理")
    @SysLog("新增预算管理")
    @PostMapping
    @PreAuthorize("@pms.hasPermission('budget_fyassetbudget_add')" )
    public R save(@RequestBody AssetBudget fyAssetBudget) {
        fyAssetBudgetService.save(fyAssetBudget);
        return R.ok(fyAssetBudget);
    }

    /**
     * 修改预算管理
     * @param fyAssetBudget 预算管理
     * @return R
     */
    @ApiOperation(value = "修改预算管理", notes = "修改预算管理")
    @SysLog("修改预算管理" )
    @PutMapping
    @PreAuthorize("@pms.hasPermission('budget_fyassetbudget_edit')" )
    public R updateById(@RequestBody AssetBudget fyAssetBudget) {
        return R.ok(fyAssetBudgetService.updateById(fyAssetBudget));
    }

    /**
     * 通过id删除预算管理
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id删除预算管理", notes = "通过id删除预算管理")
    @SysLog("通过id删除预算管理" )
    @DeleteMapping("/{id}" )
    @PreAuthorize("@pms.hasPermission('budget_fyassetbudget_del')" )
    public R removeById(@PathVariable Long id) {
        return R.ok(fyAssetBudgetService.removeById(id));
    }

    @ApiOperation(value = "批量删除预算管理", notes = "批量删除预算管理")
    @SysLog("批量删除预算管理" )
    @DeleteMapping("/batchDelete" )
    @PreAuthorize("@pms.hasPermission('budget_fyassetbudget_del')" )
    public R batchDelete(@RequestBody List<Long> ids) {
        return R.ok(fyAssetBudgetService.removeByIds(ids),String.format("成功删除%s条数据",ids.size()));
    }

    /**
     * 导出excel 表格
     * @param fyAssetBudget 查询条件
     * @return excel 文件流
     */
    @ResponseExcel
    @GetMapping("/export")
    @PreAuthorize("@pms.hasPermission('budget_fyassetbudget_export')")
    public List<BudgetExcelVO> export(AssetBudget fyAssetBudget) {
		return fyAssetBudgetService.listExcel(fyAssetBudget);
    }

	/**
	 * 获取树形
	 * @return
	 */
	@GetMapping("/tree")
	public R getTree() {
		return R.ok(fyAssetBudgetService.selectTree());
	}

	/**
	 * 导入预约信息
	 * @param excelVOList 用户列表
	 * @param bindingResult 错误信息列表
	 * @return R
	 */
	@PostMapping("/import")
	@PreAuthorize("@pms.hasPermission('budget_fyassetbudget_export')")
	public R importBudget(@RequestExcel List<BudgetExcelImportVO> excelVOList, BindingResult bindingResult) {
		return fyAssetBudgetService.importBudget(excelVOList, bindingResult);
	}

	/**
	 * 获取本地（resources）文件
	 * @param fileName 文件名称
	 * @param response 本地文件
	 */
	@SneakyThrows
	@GetMapping("/local/{fileName}")
	public void localFile(@PathVariable String fileName, HttpServletResponse response) {
		ClassPathResource resource = new ClassPathResource("file/" + fileName);
		response.setContentType("application/octet-stream; charset=UTF-8");
		IoUtil.copy(resource.getInputStream(), response.getOutputStream());
	}

	@GetMapping("/budgetTree")
	public R getBudgetTree() {
		return R.ok(fyAssetBudgetService.selectBudgetTree());
	}

    @PostMapping("/create")
    @PreAuthorize("@pms.hasPermission('budget_fyassetbudget_add')")
    public R create() {
        CloudUser user = SecurityUtils.getUser();
        AssetBudget budget = AssetBudget.builder()
                .unid(UUID.randomUUID().toString())
                .year(DateUtil.thisYear())
                .expenditureId(user.getDeptId())
                .liableId(user.getId())
                .liableName(user.getName())
                .limitThreshold("0")
                .build();
        return R.ok(budget);
    }
}
